package com.base.api.cdr;

import com.base.api.pms.PmsPublicSqlQuery;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Map;

/**
 * @author wnhuang
 * @Package com.base.api.cdr
 * @date 2020-12-31 16:58
 */
@Component
public class PatientSearch extends PmsPublicSqlQuery {

    @Override
    public String splicSql(String sql, Map<String, Object> param) {
        StringBuilder param1 = new StringBuilder();
        if (param != null) {
            if (param.get("DxDate") != null && !StringUtils.isBlank((String) (param.get("DxDate")))) {
                param1.append(" and DxDate ='" + param.get("DxDate") + "'");
            }
            if (param.get("Ap") != null && (int)param.get("Ap")==1) {
                param1.append(" AND EXISTS (SELECT 1 FROM EMR.CPOE_APP_REPORT_OPT A1 INNER JOIN EMR.CPOE_ORD_REPORT B1 ON A1.ORD_REPORT_ID = B1.ORD_REPORT_ID WHERE B1.RESULT_TYPE = 'F' AND B1.PATIENT_ID = B.PATIENT_ID)");
            }
            if (param.get("Ap") != null && (int)param.get("Ap")==2) {
                param1.append(" AND NOT EXISTS (SELECT 1 FROM EMR.CPOE_APP_REPORT_OPT A1 INNER JOIN EMR.CPOE_ORD_REPORT B1 ON A1.ORD_REPORT_ID = B1.ORD_REPORT_ID WHERE B1.RESULT_TYPE = 'F' AND B1.PATIENT_ID = B.PATIENT_ID)");
            }
            if (param.get("OPorIP") != null && !StringUtils.isBlank((String) (param.get("OPorIP")))) {
                param1.append(" and OPorIP ='" + param.get("OPorIP") + "'");
            }
            if (param.get("SexCode") != null && !StringUtils.isBlank((String) (param.get("SexCode")))) {
                param1.append(" and SEX_CODE ='" + param.get("SexCode") + "'");
            }
            if (param.get("KeyWord") != null && !StringUtils.isBlank((String) (param.get("KeyWord")))) {
                param1.append(" and " + param.get("File") + " ='" + param.get("KeyWord") + "'");
            }
            if (param.get("OrderBy") != null && !StringUtils.isBlank(String.valueOf (param.get("OrderBy")))) {
                param1.append(" ORDER BY " + param.get("OrderBy") + " DESC");
            }
        }
        return MessageFormat.format(sql.replace("'", "''"), param1.toString());
    }
}
